<template>
    <div class="app-container">
        <!-- 查询区域 -->
        <el-card class="search-card">
            <el-form :model="queryParams" :inline="true">
                <el-form-item label="功能名称">
                    <el-input v-model="queryParams.name" placeholder="请输入功能名称" clearable style="width: 250px" />
                </el-form-item>
                <el-form-item label="功能分类">
                    <el-select v-model="queryParams.categoryId" placeholder="请选择功能分类" clearable style="width: 250px">
                        <el-option v-for="item in categoryOptions" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleQuery">查询</el-button>
                    <el-button @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 数据表格区域 -->
        <el-card class="mt-2">
            <!-- 操作按钮和右侧工具栏 -->
            <el-row :gutter="20">
                <el-col :span="12">
                    <div>
                        <el-button type="primary" @click="handleAdd" icon="Plus">新增</el-button>
                        <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedRows.length"
                            icon="Delete">
                            批量删除
                        </el-button>
                    </div>
                </el-col>
                <!-- <el-col :span="12" class="flex-end">
                    <right-toolbar :search="false" v-model:showSearch="showSearch" @queryTable="fetchFeatureList"
                        :columns="columns"></right-toolbar>
                </el-col> -->
            </el-row>

            <!-- 数据表格 -->
            <el-table :data="featureList" border v-loading="loading" @selection-change="handleSelectionChange"
                class="mt-2">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column prop="id" label="ID" width="80" align="center" v-if="columns[0].visible" />
                <el-table-column prop="name" label="功能名称" align="center" v-if="columns[1].visible" />
                <el-table-column label="分类" width="120" align="center" v-if="columns[2].visible">
                    <template #default="{ row }">
                        <el-tag :type="row.categoryId === 1 ? 'primary' : 'success'">
                            {{ getCategoryLabel(row.categoryId) }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="icon" label="图标标识" align="center" width="300" v-if="columns[3].visible" />
                <el-table-column prop="clickIcon" label="图标中效果路径" width="300" align="center" v-if="columns[4].visible" />
                <el-table-column prop="path" label="页面路径" align="center" v-if="columns[5].visible" />
                <el-table-column prop="createTime" label="创建时间" width="180" align="center" v-if="columns[6].visible" />
                <el-table-column prop="updateTime" label="更新时间" width="180" align="center" v-if="columns[7].visible" />
                <el-table-column prop="sort" label="排序" width="180" align="center" v-if="columns[8].visible" />
                <el-table-column label="操作" width="180" align="center" fixed="right" v-if="columns[9].visible">
                    <template #default="{ row }">
                        <el-button size="small" @click="handleEdit(row)">编辑</el-button>
                        <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分页区域 -->
            <el-pagination class="mt-2" background layout="total, sizes, prev, pager, next, jumper" :total="total"
                v-model:page-size="queryParams.pageSize" v-model:current-page="queryParams.pageNum"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </el-card>

        <!-- 新增/编辑对话框 -->
        <el-dialog v-model="dialog.visible" :title="dialog.title" width="600px" :close-on-click-modal="false">
            <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
                <el-form-item label="功能名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入功能名称" />
                </el-form-item>
                <el-form-item label="功能分类" prop="categoryId">
                    <el-select v-model="form.categoryId" placeholder="请选择功能分类" style="width: 100%">
                        <el-option v-for="item in categoryOptions" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="图标标识">
                    <el-input v-model="form.icon" placeholder="请输入图标标识" />
                </el-form-item>
                <el-form-item label="图标选中标识">
                    <el-input v-model="form.clickIcon" placeholder="请输入图标选中标识" />
                </el-form-item>
                <el-form-item label="排序">
                    <el-input v-model="form.sort" placeholder="请输入排序" />
                </el-form-item>
                <el-form-item label="页面路径">
                    <el-input v-model="form.path" placeholder="请输入页面路径" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialog.visible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">保存</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import RightToolbar from '@/components/RightToolbar'
import {
    getFeatureCategoryList,
    listAppFeatures,
    getAppFeatureDetail,
    addAppFeature,
    updateAppFeature,
    deleteAppFeatures
} from '@/api/system/app_setting/gongneng'

// 查询参数
const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    name: '',
    categoryId: undefined
})

// 表单数据
const form = reactive({
    id: undefined,
    name: '',
    categoryId: undefined,
    icon: '',
    path: ''
})

// 对话框控制
const dialog = reactive({
    visible: false,
    title: '新增功能',
    isEdit: false
})

// 表格数据
const featureList = ref([])
const total = ref(0)
const loading = ref(false)
const selectedRows = ref([])
const formRef = ref()
const showSearch = ref(true)

// 下拉选项数据
const categoryOptions = ref([])

// 列显隐配置
const columns = ref([
    { key: 0, label: 'ID', visible: true },
    { key: 1, label: '功能名称', visible: true },
    { key: 2, label: '分类', visible: true },
    { key: 3, label: '图标标识', visible: true },
    { key: 4, label: '图标选中标识', visible: true },
    { key: 5, label: '页面路径', visible: true },
    { key: 6, label: '创建时间', visible: true },
    { key: 7, label: '更新时间', visible: true },
    { key: 8, label: '排序', visible: true },
    { key: 9, label: '操作', visible: true }

])

// 表单验证规则
const rules = reactive({
    name: [
        { required: true, message: '请输入功能名称', trigger: 'blur' }
    ],
    categoryId: [
        { required: true, message: '请选择功能分类', trigger: 'change' }
    ]
})

// 获取分类标签文本
const getCategoryLabel = (categoryId) => {
    const map = {
        1: '导航栏',
        2: '功能'
    }
    return map[categoryId] || '未知分类'
}

// 获取功能分类下拉列表
const fetchCategoryList = async () => {
    try {
        const res = await getFeatureCategoryList()
        categoryOptions.value = res.data || []
    } catch (error) {
        console.error('获取功能分类列表失败:', error)
        ElMessage.error('获取功能分类列表失败')
    }
}

// 获取功能列表
const fetchFeatureList = async () => {
    try {
        loading.value = true
        const res = await listAppFeatures(queryParams)
        featureList.value = res.rows || []
        total.value = res.total || 0
    } catch (error) {
        console.error('获取功能列表失败:', error)
        ElMessage.error('获取功能列表失败')
    } finally {
        loading.value = false
    }
}

// 查询按钮
const handleQuery = () => {
    queryParams.pageNum = 1
    fetchFeatureList()
}

// 重置查询
const resetQuery = () => {
    queryParams.pageNum = 1
    queryParams.name = ''
    queryParams.categoryId = undefined
    fetchFeatureList()
}

// 分页大小变化
const handleSizeChange = (size) => {
    queryParams.pageSize = size
    fetchFeatureList()
}

// 当前页码变化
const handleCurrentChange = (page) => {
    queryParams.pageNum = page
    fetchFeatureList()
}

// 表格选择变化
const handleSelectionChange = (selection) => {
    selectedRows.value = selection
}

// 新增按钮
const handleAdd = () => {
    dialog.visible = true
    dialog.title = '新增功能'
    dialog.isEdit = false
    resetForm()
}

// 编辑按钮
const handleEdit = async (row) => {
    try {
        const res = await getAppFeatureDetail(row.id)
        Object.assign(form, res.data)
        dialog.visible = true
        dialog.title = '编辑功能'
        dialog.isEdit = true
    } catch (error) {
        console.error('获取功能详情失败:', error)
        ElMessage.error('获取功能详情失败')
    }
}

// 删除按钮
const handleDelete = (row) => {
    ElMessageBox.confirm(`确认删除功能 "${row.name}" 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        return deleteAppFeatures([row.id])
    }).then(() => {
        ElMessage.success('删除成功')
        fetchFeatureList()
    }).catch(() => { })
}

// 批量删除
const handleBatchDelete = () => {
    if (selectedRows.value.length === 0) {
        ElMessage.warning('请至少选择一条记录')
        return
    }

    const names = selectedRows.value.map(item => item.name).join(', ')

    ElMessageBox.confirm(`确认删除选中的 ${selectedRows.value.length} 条记录吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        const ids = selectedRows.value.map(item => item.id)
        return deleteAppFeatures(ids)
    }).then(() => {
        ElMessage.success('删除成功')
        fetchFeatureList()
    }).catch(() => { })
}

// 重置表单
const resetForm = () => {
    form.id = undefined
    form.name = ''
    form.categoryId = undefined
    form.icon = ''
    form.path = ''
    if (formRef.value) {
        formRef.value.resetFields()
    }
}

// 提交表单
const submitForm = async () => {
    try {
        await formRef.value.validate()

        if (dialog.isEdit) {
            await updateAppFeature(form)
            ElMessage.success('更新成功')
        } else {
            await addAppFeature(form)
            ElMessage.success('新增成功')
        }

        dialog.visible = false
        fetchFeatureList()
    } catch (error) {
        console.error('保存失败:', error)
        if (error !== 'validate') {
            ElMessage.error('操作失败')
        }
    }
}

// 初始化加载数据
onMounted(() => {
    fetchCategoryList()
    fetchFeatureList()
})
</script>

<style scoped>
.app-container {
    padding: 20px;
}

.search-card {
    margin-bottom: 20px;
}

.mt-2 {
    margin-top: 20px;
}

.flex-end {
    display: flex;
    justify-content: flex-end;
    align-items: center;
}

/* 表格列宽自适应 */
:deep(.el-table) {
    width: 100%;
}

:deep(.el-table__cell) {
    padding: 12px 0;
}
</style>